/**
 * 消息搜索管理器
 */
class MessageSearch {
    constructor(options) {
        this.messages = options.messages || [];
        this.searchInput = options.searchInput;
        this.searchResultsContainer = options.searchResultsContainer;
        this.onResultClick = options.onResultClick;
        
        this.init();
    }
    
    init() {
        // 初始化搜索输入事件
        this.searchInput.addEventListener('input', this.handleSearch.bind(this));
        this.searchInput.addEventListener('keydown', (e) => {
            if (e.key === 'Enter') {
                this.handleSearch();
            }
        });
    }
    
    /**
     * 更新消息数据
     * @param {Array} messages 消息数组
     */
    updateMessages(messages) {
        this.messages = messages;
    }
    
    /**
     * 处理搜索
     */
    handleSearch() {
        const query = this.searchInput.value.trim();
        if (!query) {
            this.clearResults();
            return;
        }
        
        const results = this.searchMessages(query);
        this.displayResults(results);
    }
    
    /**
     * 搜索消息
     * @param {string} query 搜索关键词
     * @returns {Array} 搜索结果
     */
    searchMessages(query) {
        const results = [];
        const lowerQuery = query.toLowerCase();
        
        this.messages.forEach((message, index) => {
            // 跳过系统消息
            if (message.sender === 'system') return;
            
            // 检查消息内容是否匹配
            const content = message.content.toLowerCase();
            if (content.includes(lowerQuery)) {
                results.push({
                    message,
                    index,
                    matches: this.findMatches(message.content, query)
                });
            }
        });
        
        return results;
    }
    
    /**
     * 查找匹配位置
     * @param {string} content 消息内容
     * @param {string} query 搜索词
     * @returns {Array} 匹配位置数组
     */
    findMatches(content, query) {
        const matches = [];
        const lowerContent = content.toLowerCase();
        const lowerQuery = query.toLowerCase();
        
        let pos = 0;
        while ((pos = lowerContent.indexOf(lowerQuery, pos)) >= 0) {
            matches.push({
                start: pos,
                end: pos + query.length
            });
            pos += query.length;
        }
        
        return matches;
    }
    
    /**
     * 显示搜索结果
     * @param {Array} results 搜索结果数组
     */
    displayResults(results) {
        this.clearResults();
        
        if (results.length === 0) {
            const noResults = document.createElement('div');
            noResults.className = 'search-no-results';
            noResults.textContent = '没有找到匹配的消息';
            this.searchResultsContainer.appendChild(noResults);
            return;
        }
        
        results.forEach(result => {
            const resultElement = this.createResultElement(result);
            this.searchResultsContainer.appendChild(resultElement);
        });
    }
    
    /**
     * 创建搜索结果元素
     * @param {Object} result 搜索结果
     * @returns {HTMLElement}
     */
    createResultElement(result) {
        const { message, index, matches } = result;
        
        const element = document.createElement('div');
        element.className = 'search-result';
        element.dataset.index = index;
        
        // 添加发送者信息
        const sender = document.createElement('div');
        sender.className = 'search-result-sender';
        sender.textContent = message.sender === 'user' ? '你' : '小智';
        element.appendChild(sender);
        
        // 添加时间戳
        const time = document.createElement('div');
        time.className = 'search-result-time';
        time.textContent = this.formatTime(message.timestamp);
        element.appendChild(time);
        
        // 添加高亮显示的消息内容
        const content = document.createElement('div');
        content.className = 'search-result-content';
        content.innerHTML = this.highlightMatches(message.content, matches);
        element.appendChild(content);
        
        // 添加点击事件
        element.addEventListener('click', () => {
            if (this.onResultClick) {
                this.onResultClick(index);
            }
        });
        
        return element;
    }
    
    /**
     * 高亮显示匹配内容
     * @param {string} content 消息内容
     * @param {Array} matches 匹配位置数组
     * @returns {string} 带高亮标记的HTML
     */
    highlightMatches(content, matches) {
        if (matches.length === 0) return content;
        
        let highlighted = '';
        let lastPos = 0;
        
        matches.forEach(match => {
            // 添加匹配前的内容
            highlighted += content.substring(lastPos, match.start);
            // 添加高亮匹配内容
            highlighted += `<span class="search-highlight">${content.substring(match.start, match.end)}</span>`;
            lastPos = match.end;
        });
        
        // 添加剩余内容
        highlighted += content.substring(lastPos);
        
        return highlighted;
    }
    
    /**
     * 格式化时间戳
     * @param {string} timestamp ISO时间字符串
     * @returns {string} 格式化后的时间
     */
    formatTime(timestamp) {
        const date = new Date(timestamp);
        return date.toLocaleString();
    }
    
    /**
     * 清空搜索结果
     */
    clearResults() {
        this.searchResultsContainer.innerHTML = '';
    }
    
    /**
     * 销毁搜索管理器
     */
    destroy() {
        this.searchInput.removeEventListener('input', this.handleSearch);
        this.clearResults();
    }
}

/**
 * 初始化消息搜索功能
 * @param {Object} options 配置选项
 * @returns {MessageSearch} 搜索管理器实例
 */
function initMessageSearch(options) {
    return new MessageSearch(options);
}